<template>
  <div v-if="hasError" class="error-boundary">
    <el-card class="error-card">
      <template #header>
        <div class="card-header">
          <el-icon :size="20"><Warning /></el-icon>
          <span>发生错误</span>
        </div>
      </template>
      <div class="error-content">
        <p>抱歉，组件渲染时发生了错误。</p>
        <p class="error-message">{{ errorMessage }}</p>
        <div class="error-actions">
          <el-button type="primary" @click="handleRetry">重试</el-button>
          <el-button @click="handleGoHome">返回首页</el-button>
        </div>
      </div>
    </el-card>
  </div>
  <slot v-else />
</template>

<script setup lang="ts">
import { ref, onErrorCaptured } from 'vue'
import { useRouter } from 'vue-router'
import { Warning } from '@element-plus/icons-vue'

const hasError = ref(false)
const errorMessage = ref('')
const router = useRouter()

// 捕获子组件错误
onErrorCaptured((err, instance, info) => {
  hasError.value = true
  errorMessage.value = err.message || '未知错误'
  console.error('Error captured:', err, info)

  // 返回 false 阻止错误继续传播
  return false
})

const handleRetry = () => {
  hasError.value = false
  errorMessage.value = ''
}

const handleGoHome = () => {
  router.push('/')
}
</script>

<style scoped lang="scss">
.error-boundary {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 20px;

  .error-card {
    width: 100%;
    max-width: 500px;

    .card-header {
      display: flex;
      align-items: center;
      gap: 8px;
      color: #f56c6c;
    }

    .error-content {
      text-align: center;

      .error-message {
        color: #909399;
        font-size: 14px;
        margin: 20px 0;
        padding: 10px;
        background-color: #f4f4f5;
        border-radius: 4px;
      }

      .error-actions {
        display: flex;
        justify-content: center;
        gap: 10px;
      }
    }
  }
}
</style>
